package com.sgb.kjwl.view.ui.activity.enterprise;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.databinding.ActivityCreateBuyMakeoverBinding;
import com.sgb.kjwl.model.entity.enterprise.CopyrightEntity;
import com.sgb.kjwl.model.entity.enterprise.PatentDetailEntity;
import com.sgb.kjwl.model.entity.enterprise.TrademarkEntity;
import com.sgb.kjwl.utils.PointUtils;
import com.swgk.core.util.UiUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.kjwl.view.ui.adapter.enterprise.TextViewBindingAdapter;
import com.sgb.kjwl.viewmodel.enterprise.CreateBuyMakeOverOrderViewModel;
import com.sgb.link.constant.RequestCode;
import com.swgk.core.base.model.entity.ContactsEntitiy;
import com.swgk.core.base.model.entity.InvoicingInfoEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

public class CreateBuyMakeOverOrderActivity extends AppActivity {

    private ActivityCreateBuyMakeoverBinding mBinding;
    private CreateBuyMakeOverOrderViewModel mViewModel;

    public static final int REQUEST_CODE_CONTANCTS = 1153;
    public static final int REQUEST_CODE_RECEIPT = 1154;


    public static void startactivity(Context mContext, String jsonObject, String detailType, String sellerPhone) {
        Intent mIntent = new Intent();
        mIntent.setClass(mContext, CreateBuyMakeOverOrderActivity.class);
        mIntent.putExtra("jsondata", jsonObject);
        mIntent.putExtra("detailType", detailType);
        mIntent.putExtra("sellerPhone", sellerPhone);
        mContext.startActivity(mIntent);
    }

    @Override
    protected void initView() {
        super.initView();
        mViewModel = new ViewModelProvider(this).get(CreateBuyMakeOverOrderViewModel.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_create_buy_makeover);
        mBinding.setVariable(BR.mviewmodel, mViewModel);
        mBinding.setLifecycleOwner(this);
    }

    @Override
    protected void init() {
        super.init();
        mViewModel.detailType = getIntent().getStringExtra("detailType");
        mViewModel.sellerPhone = getIntent().getStringExtra("sellerPhone");
        String jsondata = getIntent().getStringExtra("jsondata");
        if (!TextUtils.isEmpty(jsondata)) {
            switch (mViewModel.detailType) {
                case "商标":
                    mViewModel.trademarkEntity = JSONObject.parseObject(jsondata, TrademarkEntity.class);
                    setTrademarKEntityData();
                    break;
                case "版权":
                    mViewModel.copyrightEntity = JSONObject.parseObject(jsondata, CopyrightEntity.class);
                    Log.e("message", new Gson().toJson(mViewModel.copyrightEntity));
                    setcopyrightEntityData();
                    break;
                case "专利":
                    mViewModel.patentDetailEntity = JSONObject.parseObject(jsondata, PatentDetailEntity.class);
                    setpatentDetailEntityData();
                    break;
            }
        }

        initObsever();
        mBinding.etSelfIntroduction.setShowBottomNumber(false);
        mBinding.tvChoiceLinkman.setOnClickListener(this);
        mBinding.tvZankan.setOnClickListener(this);
        mBinding.imageArrow.setOnClickListener(this);
        mBinding.tvChoiceReceipt.setOnClickListener(this);
        mBinding.tvBtnChoicereceipt.setOnClickListener(this);
        mBinding.layoutReceipt.tvZankanR.setOnClickListener(this);
        mBinding.layoutReceipt.imageArrowR.setOnClickListener(this);
        mBinding.tvCreateName.setOnClickListener(this);
        mViewModel.getContanctsList();
        mViewModel.getReceiptList();
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_choice_linkman:
//                ContanctsActivity.startactivityForResult(CreateBuyMakeOverOrderActivity.this, REQUEST_CODE_CONTANCTS);
                Intent mIntent = new Intent(getActivity(), ContanctsActivity.class);
                mIntent.putExtra("request", true);
                startActivityForResult(mIntent, REQUEST_CODE_CONTANCTS);
                break;
            case R.id.tv_zankan:
            case R.id.image_arrow:
                mViewModel.show_cnotans_more.postValue(!mViewModel.show_cnotans_more.getValue());
                break;
            case R.id.tv_zankan_r:
            case R.id.image_arrow_r:
                mViewModel.show_recepist_more.postValue(!mViewModel.show_recepist_more.getValue());
                break;
            case R.id.tv_btn_choicereceipt:
            case R.id.tv_choice_receipt:
//                ReceIptActivity.startactivityForResult(CreateBuyMakeOverOrderActivity.this, REQUEST_CODE_RECEIPT);
                Intent mIntent1 = new Intent(getActivity(), ReceIptActivity.class);
                startActivityForResult(mIntent1, REQUEST_CODE_RECEIPT);
                break;

            case R.id.tv_create_name:
                MToast.showLongToast(this, "功能开发中，敬请期待！");
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("requestCode", requestCode + "");
        Log.e("resultCode", resultCode + "");

        switch (resultCode) {
            case RequestCode.CODE_ZERO:
                try {

                    if (REQUEST_CODE_CONTANCTS == requestCode && data.getSerializableExtra("data") != null) {
                        showContanctsUser((ContactsEntitiy) data.getSerializableExtra("data"));
                    }
                    if (REQUEST_CODE_RECEIPT == requestCode && data.getSerializableExtra("data") != null) {
                        mViewModel.show_recepist_more.postValue(false);
                        mViewModel.recepiydata.postValue((InvoicingInfoEntity) data.getSerializableExtra("data"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void initObsever() {
        mViewModel.ToastShow.observe(this, data -> {
            MToast.showLongToast(this, data);
        });

        mViewModel.showloading.observe(this, type_int -> {
            switch (type_int) {
                case 1:
                    DialogHelper.showProgressDialog(getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    DialogHelper.dismissProgressDialog();
                    break;

                case 3:
                    AddNeedQuoteResultActivity.start(this, false, false);
                    break;
            }
        });

        mViewModel.show_cnotans_more.observe(this, show -> {
            mBinding.imageArrow.setImageResource(show ? R.mipmap.btn_expand_up_gray : R.mipmap.btn_close);
        });

        mViewModel.show_recepist_more.observe(this, show -> {
            mBinding.layoutReceipt.tvZankanR.setText(show ? "收起" : "展开");
            mBinding.layoutReceipt.linRecepitBank.setVisibility(show ? View.VISIBLE : View.GONE);
            mBinding.layoutReceipt.linRecepitBanknum.setVisibility(show ? View.VISIBLE : View.GONE);
            mBinding.layoutReceipt.linRecepitCompanypath.setVisibility(show ? View.VISIBLE : View.GONE);
            mBinding.layoutReceipt.linRecepitCompanyphone.setVisibility(show ? View.VISIBLE : View.GONE);
            mBinding.layoutReceipt.imageArrowR.setImageResource(show ? R.mipmap.btn_expand_up_gray : R.mipmap.btn_close);
        });

        /***联系人列表回调**/
        mViewModel.list_contancts.observe(this, listdata -> {
            if (listdata.size() > 0) {
                if (!TextUtils.isEmpty(listdata.get(0).getStatus()) && listdata.get(0).getStatus().equals("0")) {
                    showContanctsUser(listdata.get(0));
                } else {
                    mBinding.tvChoiceLinkman.setText("选择联系人");
                    mBinding.tvLinkTips.setText("还未选择联系人信息，请及时选择！");
                    mBinding.linLinkView.setVisibility(View.GONE);
                    mBinding.linNullLink.setVisibility(View.VISIBLE);
                }

            } else {//联系人暂无数据
                mBinding.tvChoiceLinkman.setText("添加联系人");
                mBinding.tvLinkTips.setText("还未添加联系人信息，请及时添加！");
                mBinding.linLinkView.setVisibility(View.GONE);
                mBinding.linNullLink.setVisibility(View.VISIBLE);
            }
        });

        /***开票列表回调***/
        mViewModel.list_recepiy.observe(this, listdata -> {
            if (listdata.size() > 0) {
                if (listdata.get(0).getIsDefault() == 1) {
                    mViewModel.recepiydata.postValue(listdata.get(0));
                } else {
                    mBinding.imageArrowReceipt.setVisibility(View.GONE);
                    mBinding.tvChoiceReceipt.setVisibility(View.GONE);
                    mBinding.layoutReceipt.linMainview.setVisibility(View.GONE);
                    mBinding.linRecepitNull.setVisibility(View.VISIBLE);
                    mBinding.tvBtnChoicereceipt.setVisibility(View.VISIBLE);
                    mBinding.tvRecepitTips.setText("还未选择开票信息，请及时选择！");
                }
            } else {
                mBinding.tvChoiceReceipt.setVisibility(View.GONE);
                mBinding.layoutReceipt.linMainview.setVisibility(View.GONE);
                mBinding.linRecepitNull.setVisibility(View.VISIBLE);
                mBinding.tvBtnChoicereceipt.setVisibility(View.GONE);
                mBinding.imageArrowReceipt.setVisibility(View.GONE);
                mBinding.tvRecepitTips.setText(UserOperating.getInstance().isCompany() ? "您关联的企业还未完善开票信息，请联系企业账号负责人去PC端处理，即可下单！" : "您还未完善开票信息，请前往PC端操作后再下单！");
            }
        });


        mViewModel.message.observe(this, data -> {
            if (data == null) {
                MToast.showToast(CreateBuyMakeOverOrderActivity.this, "接口异常");
                return;
            }
            if (data.equals(APIManager.RESPONSE_OK)) {
                EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.EVENT_CREATE_MAKEOVERORDER_SECESS));
                if (!TextUtils.isEmpty(mViewModel.orderid)) {
                    SumitMakeOverOrderResultActivity.startactivity(getActivity(), true, mViewModel.orderid, mViewModel.detailType);
                }
            } else {
                SumitMakeOverOrderResultActivity.startactivity(getActivity(), false, data, mViewModel.detailType);
            }
            finish();
        });
        mViewModel.recepiydata.observe(this, data -> {
            mBinding.linRecepitNull.setVisibility(View.GONE);
            mBinding.tvBtnChoicereceipt.setVisibility(View.GONE);
            mBinding.layoutReceipt.linMainview.setVisibility(View.VISIBLE);
            mBinding.tvChoiceReceipt.setVisibility(View.VISIBLE);
            mBinding.tvChoiceReceipt.setText("切换开票信息");

        });
    }


    private void showContanctsUser(ContactsEntitiy linkedata) {
        mViewModel.show_cnotans_more.postValue(false);
        mBinding.tvChoiceLinkman.setText("切换联系人");
        mBinding.linNullLink.setVisibility(View.GONE);
        mBinding.linLinkView.setVisibility(View.VISIBLE);
        mViewModel.linkdata = linkedata;
        mBinding.tvLinkUsername.setText(TextUtils.isEmpty(linkedata.getContactName()) ? "/" : linkedata.getContactName());
        mBinding.tvIsmoren.setVisibility("0".equals(linkedata.getStatus()) ? View.VISIBLE : View.GONE);
        mBinding.tvLinkPhone.setText(TextUtils.isEmpty(linkedata.getContactPhone()) ? "/" : linkedata.getContactPhone());
        mBinding.tvLinkEmailno.setText(TextUtils.isEmpty(linkedata.getPostCode()) ? "/" : linkedata.getPostCode());
        mBinding.tvLinZw.setText(TextUtils.isEmpty(linkedata.getPosition()) ? "/" : linkedata.getPosition());
        mBinding.tvLinkCompanyname.setText(TextUtils.isEmpty(linkedata.getCompanyName()) ? "/" : linkedata.getCompanyName());
        String path = "";
        if (!TextUtils.isEmpty(linkedata.getProvinceName())) {
            path = path + linkedata.getProvinceName();
        }
        if (!TextUtils.isEmpty(linkedata.getCityName())) {
            path = path + linkedata.getCityName();
        }
        if (!TextUtils.isEmpty(linkedata.getAreaName())) {
            path = path + linkedata.getAreaName();
        }
        if (!TextUtils.isEmpty(linkedata.getAddress())) {
            path = path + linkedata.getAddress();
        }
        mBinding.tvLinkPath.setText(TextUtils.isEmpty(path) ? "/" : path);
    }


    private void setTrademarKEntityData() {
        switch (mViewModel.trademarkEntity.getPublishType()) {
            case 0://个人
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.trademarkEntity.getUserRealName()) ? "/" : mViewModel.trademarkEntity.getUserRealName());
                break;
            case 1://公司
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.trademarkEntity.getCompanyName()) ? "/" : mViewModel.trademarkEntity.getCompanyName());
                break;
            case 2://团队
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.trademarkEntity.getRealName()) ? "/" : mViewModel.trademarkEntity.getRealName());
                break;


        }

        mBinding.tvName.setText("商标名称：" + (TextUtils.isEmpty(mViewModel.trademarkEntity.getName()) ? "/" : mViewModel.trademarkEntity.getName()));
        mBinding.tvType1.setText("商标分类：" + (TextUtils.isEmpty(mViewModel.trademarkEntity.getCategoryName()) ? "/" : mViewModel.trademarkEntity.getCategoryName()));
        mBinding.tvType2.setText("商标注册号：" + (TextUtils.isEmpty(mViewModel.trademarkEntity.getRegistrationNo()) ? "/" : mViewModel.trademarkEntity.getRegistrationNo()));
        mBinding.tvPrice.setText(mViewModel.trademarkEntity.getPrice() == -1 ? "议价" : TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(mViewModel.trademarkEntity.getPrice())));
        mBinding.tvPrice2.setText(mViewModel.trademarkEntity.getPrice() == -1 ? "议价" : TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(mViewModel.trademarkEntity.getPrice())));
        Glide.with(UiUtil.getContext()).load(mViewModel.trademarkEntity.getImg()).into(mBinding.imageGoods);
    }

    private void setcopyrightEntityData() {
        switch (mViewModel.copyrightEntity.getPublishType()) {
            case 0://个人
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.copyrightEntity.getUserRealName()) ? "/" : mViewModel.copyrightEntity.getUserRealName());
                break;
            case 1://公司
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.copyrightEntity.getCompanyName()) ? "/" : mViewModel.copyrightEntity.getCompanyName());
                break;
            case 2://团队
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.copyrightEntity.getRealName()) ? "/" : mViewModel.copyrightEntity.getRealName());
                break;

        }
        mBinding.tvName.setText("版权名称：" + (TextUtils.isEmpty(mViewModel.copyrightEntity.getName()) ? "/" : mViewModel.copyrightEntity.getName()));
        mBinding.tvType1.setText("版权分类：" + (TextUtils.isEmpty(mViewModel.copyrightEntity.getCategoryName()) ? "/" : mViewModel.copyrightEntity.getCategoryName()));
        mBinding.tvType2.setText("登记号：" + (TextUtils.isEmpty(mViewModel.copyrightEntity.getRegistrationNo()) ? "/" : mViewModel.copyrightEntity.getRegistrationNo()));
        mBinding.tvPrice.setText(mViewModel.copyrightEntity.getPrice() == -1 ? "议价" : TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(mViewModel.copyrightEntity.getPrice())));
        mBinding.tvPrice2.setText(mViewModel.copyrightEntity.getPrice() == -1 ? "议价" : TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(mViewModel.copyrightEntity.getPrice())));
        Glide.with(UiUtil.getContext()).load(mViewModel.copyrightEntity.getImg()).into(mBinding.imageGoods);
    }

    private void setpatentDetailEntityData() {
        switch (mViewModel.patentDetailEntity.getPublishType()) {
            case 0://个人
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.patentDetailEntity.getUserRealName()) ? "/" : mViewModel.patentDetailEntity.getUserRealName());
                break;
            case 1://公司
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.patentDetailEntity.getCompanyName()) ? "/" : mViewModel.patentDetailEntity.getCompanyName());
                break;
            case 2://团队
                mBinding.tvCreateName.setText(TextUtils.isEmpty(mViewModel.patentDetailEntity.getRealName()) ? "/" : mViewModel.patentDetailEntity.getRealName());
                break;

        }
        mBinding.tvPrice2.setText(mViewModel.patentDetailEntity.getPrice() == -1 ? "议价" : TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(mViewModel.patentDetailEntity.getPrice())));
        mBinding.tvName.setText("专利名称：" + (TextUtils.isEmpty(mViewModel.patentDetailEntity.getName()) ? "/" : mViewModel.patentDetailEntity.getName()));
        mBinding.tvType1.setText("专利类型：" + (TextUtils.isEmpty(mViewModel.patentDetailEntity.getCategoryName()) ? "/" : mViewModel.patentDetailEntity.getCategoryName()));
        mBinding.tvType2.setText("专利注册号：" + (TextUtils.isEmpty(mViewModel.patentDetailEntity.getRegistrationNo()) ? "/" : mViewModel.patentDetailEntity.getRegistrationNo()));
        mBinding.tvPrice.setText(mViewModel.patentDetailEntity.getPrice() == -1 ? "议价" : TextViewBindingAdapter.setMoneyForRMB("￥" + PointUtils.price(mViewModel.patentDetailEntity.getPrice())));
        if (!TextUtils.isEmpty(mViewModel.patentDetailEntity.getImg())) {
            Glide.with(UiUtil.getContext()).load(mViewModel.patentDetailEntity.getImg()).into(mBinding.imageGoods);
        } else {
            switch (mViewModel.patentDetailEntity.getCategoryName()) {
                case "发明专利":
                    Glide.with(UiUtil.getContext()).load(R.mipmap.qiyefuwu_module_famingzhuanli_for_patent_publish).into(mBinding.imageGoods);
                    break;
                case "实用新型":
                    Glide.with(UiUtil.getContext()).load(R.mipmap.shiyongxinxing_patent_publish).into(mBinding.imageGoods);
                    break;
                case "外观设计":
                    Glide.with(UiUtil.getContext()).load(R.mipmap.waiguansheji_patent_publish).into(mBinding.imageGoods);
                    break;
            }
        }
    }


}
